﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using RealEstate.Models;

namespace RealEstate.Views.Account
{
    public partial class EditUser : System.Web.UI.Page
    {
        private Client _client;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var clientId = Request.QueryString["id"];

                if (!string.IsNullOrEmpty(clientId))
                {
                    var clientEntity = new ClientEntities();
                    _client = clientEntity.GetById(Int32.Parse(clientId));
                    if (_client != null)
                    {
                        ClientId.Value = _client.ClientId.ToString();
                        if (!string.IsNullOrEmpty(_client.FullName))
                            ClientName.Text = _client.FullName;

                        if (_client.UserId != null)
                        {
                            var user = Membership.GetUser(_client.UserId);
                            if (user != null)
                            {
                                Username.Text = user.UserName;
                                Password.Text = user.GetPassword();
                                Username.Enabled = false;
                                IsActive.Checked = user.IsApproved;
                                UserId.Value = _client.UserId.ToString();
                                btnCreate.Text = "Update User";
                            }
                        }
                    }
                }
                else
                {
                    Response.Redirect("~/Account/NewUser.aspx");
                }
            }
        }
        protected void btnCreate_Click(object sender, EventArgs e)
        {
            string sUserName = Username.Text;
            string sPassword = Password.Text;
            const string sEmail = "default@abc.com";

            if (string.IsNullOrEmpty(UserId.Value))
            {
                MembershipCreateStatus createStatus;
                MembershipUser newUser = Membership.CreateUser(HttpUtility.HtmlEncode(sUserName.Trim()),
                                        HttpUtility.HtmlEncode(sPassword.Trim()),
                                            HttpUtility.HtmlEncode(sEmail.Trim()),
                                            "1",
                                            "1",
                                           IsActive.Checked,
                                         out createStatus);
                string createResultMessage = "";
                switch (createStatus)
                {
                    case MembershipCreateStatus.Success:
                        createResultMessage = "&raquo; The user was successfully created. &laquo;";
                        break;
                    case MembershipCreateStatus.InvalidUserName:
                        createResultMessage = "The user name was not found in the database.";
                        break;
                    case MembershipCreateStatus.InvalidPassword:
                        createResultMessage = "The password is not formatted correctly.";
                        break;
                    case MembershipCreateStatus.InvalidQuestion:
                        createResultMessage = "The password question is not formatted correctly.";
                        break;
                    case MembershipCreateStatus.InvalidAnswer:
                        createResultMessage = "The password answer is not formatted correctly.";
                        break;
                    case MembershipCreateStatus.InvalidEmail:
                        createResultMessage = "The e-mail address is not formatted correctly.";
                        break;
                    case MembershipCreateStatus.DuplicateUserName:
                        createResultMessage = "The user name already exists in the database for the application.";
                        break;
                    case MembershipCreateStatus.DuplicateEmail:
                        createResultMessage = "The e-mail address already exists in the database for the application.";
                        break;
                    case MembershipCreateStatus.UserRejected:
                        createResultMessage = "The user was not created, for a reason defined by the provider.";
                        break;
                    case MembershipCreateStatus.InvalidProviderUserKey:
                        createResultMessage = "The provider user key is of an invalid type or format.";
                        break;
                    case MembershipCreateStatus.DuplicateProviderUserKey:
                        createResultMessage = "The ProviderUserKey already exists in the database for the application.";
                        break;
                    case MembershipCreateStatus.ProviderError:
                        createResultMessage = "The provider returned an error that is not described by other ";
                        createResultMessage += "MembershipCreateStatus enumeration values.";
                        break;
                }

                if (createStatus != MembershipCreateStatus.Success)
                {
                    InvalidCredentialsMessage.Visible = true;
                    InvalidCredentialsMessage.Text = createResultMessage;
                }
                else
                {
                    var clientEntity = new ClientEntities();
                    _client = clientEntity.GetById(Int32.Parse(ClientId.Value));
                    if (_client != null && newUser != null && newUser.ProviderUserKey != null)
                    {
                        _client.UserId = Guid.Parse(newUser.ProviderUserKey.ToString());
                        try
                        {
                            clientEntity.Update(_client);
                            InvalidCredentialsMessage.Visible = true;
                            InvalidCredentialsMessage.Text = "User created successfully!";
                            Username.Enabled = false;
                            UserId.Value = _client.UserId.ToString();
                            btnCreate.Text = "Update User";
                        }
                        catch(ArgumentException ex)
                        {
                            InvalidCredentialsMessage.Visible = true;
                            InvalidCredentialsMessage.Text = "User not created, please try again. ";
                            InvalidCredentialsMessage.Text += ex.Message;
                        }
                    }
                }
            }
            else
            {
                string updateResultMessage = string.Empty;
                var updateUser = Membership.GetUser(Username.Text);
                try
                {
                    if (updateUser != null)
                    {
                        if (updateUser.ChangePassword(updateUser.GetPassword(), Password.Text))
                        {
                            updateUser.IsApproved = IsActive.Checked;
                            Membership.UpdateUser(updateUser);
                            updateResultMessage = "User updated successfully!";
                        }
                        else
                        {
                            updateResultMessage = "User not changed, please try again.";
                        }
                    }
                }
                catch (ArgumentException ex)
                {
                    updateResultMessage += "<br/> " + ex.Message;
                }

                InvalidCredentialsMessage.Visible = true;
                InvalidCredentialsMessage.Text = updateResultMessage;
                Response.Redirect("ManageUsers.aspx");
            }
        }
    }
}